import os  
import re  
import moviepy.editor as mp  
  
def extract_audio(video_file_path):  
    my_clip = mp.VideoFileClip(video_file_path)  
    # 使用原始文件名（不包括扩展名）来命名音频文件  
    base_name = os.path.splitext(video_file_path)[0]  
    my_clip.audio.write_audiofile(f'{base_name}.mp3')  
  
def convert_mp4_to_mp3_in_directory(directory='.'):  
    # 列出目录中的所有文件  
    files = os.listdir(directory)  
    # 使用正则表达式匹配所有以 .mp4 结尾的文件  
    mp4_files = [f for f in files if re.search(r'\.mp4$', f)]  
      
    for mp4_file in mp4_files:  
        # 构造文件的完整路径  
        full_path = os.path.join(directory, mp4_file)  
        # 提取音频并保存为 mp3  
        extract_audio(full_path)  
        print(f"Converted {mp4_file} to {os.path.splitext(mp4_file)[0]}.mp3")  
  
# 调用函数，默认转换当前目录下的所有 .mp4 文件  
convert_mp4_to_mp3_in_directory()